package com.hrt.datasender.process.strategy.hj212.util;

import com.btcode.db.result.Row;
import com.btcode.db.sqlparameter.SQLParameterList;
import com.hrt.datasender.datadao.model.BcSendPlatformModel;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.PacketModel;
import com.hrt.db.DBManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class StrategyUtil {
	/**
	 * 返回请求应答
	 * @param sendPlatform
	 * @param msg
	 * @param state  0:请求应答  1：执行结果
	 * @return
	 */
	public static void responseMsg(BcSendPlatformModel sendPlatform, String msg, String state, String exeRtn) {
		/**
		 * 获取msg内容
		 */
		HashMap<String, String> dataValue = new HashMap<>();
		msg = msg.substring(6);
		String parmValueStrs[] = msg.split(";");
		for (String parmValueStr : parmValueStrs) {
			String[] parmValue = parmValueStr.split("=");
			if (parmValue.length < 2) {
				continue;
			}
			dataValue.put(parmValue[0], parmValue[1]);
		}

		String cp;
		StringBuilder strBuilder = new StringBuilder();
		if("0".equals(state)){
			/**
			 * QN=20160801085857223;ST=91;CN=9011;PW=123456;MN=010000A8900016F000169DC0;Flag=4;CP=&&QnRtn=1&&
			 * 构造反馈报文
			 */
			strBuilder.append("QN=" + dataValue.get("QN")+";");
			strBuilder.append("ST=91;");
			strBuilder.append("CN=9011;");
			strBuilder.append("PW=123456;");
			strBuilder.append("MN=" + sendPlatform.getMn() + ";");
			strBuilder.append("Flag=4;");
			cp = "QnRtn=1";
			strBuilder.append("CP=&&" + cp + "&&;");
		}
		else{
			/**
			 * QN=20160801085857223;ST=91;CN=9012;PW=123456;MN=010000A8900016F000169DC0;Flag=4;CP=&&ExeRtn=1&&
			 * 构造执行结果报文
			 */
			strBuilder.append("QN=" + dataValue.get("QN")+";");
			strBuilder.append("ST=91;");
			strBuilder.append("CN=9012;");
			strBuilder.append("PW=123456;");
			strBuilder.append("MN=" + sendPlatform.getMn() + ";");
			strBuilder.append("Flag=4;");
			cp = "ExeRtn=" + exeRtn;
			strBuilder.append("CP=&&" + cp + "&&;");
		}

		/**
		 * 插入包头包尾
		 */
		String crcStr = CRCUtil.calcCRC(strBuilder.toString());
		String dataLength = strBuilder.length() + "";
		final int dataLengthFormat = 4;
		while (dataLength.length() < dataLengthFormat) {
			dataLength = "0" + dataLength;
		}
		strBuilder.insert(0, "##" + dataLength);
		strBuilder.append(crcStr + "\r\n");

		/**
		 * 插入数据到反馈队列中去
		 */
		PacketModel model = new PacketModel();
		model.setIp(sendPlatform.getIp());
		model.setPort(sendPlatform.getPort());
		model.setMn(sendPlatform.getMn());
		model.setMsg(strBuilder.toString());
		MqKit.productMsgToRecriminateMQ(model);
	}

	/**
	 * 往组态数据库插入反控命令
	 * @param msg
	 */
	public static String insertRcCmd(String msg){
		msg = msg.substring(6,msg.length()-4);
		String id =  UUID.randomUUID().toString();
		String sql = "insert into RemoteControlT_Report(CMD_ID,CMD_MSG) values (@CMD_ID,@CMD_MSG)";
		SQLParameterList pc = new SQLParameterList();
		pc.put("CMD_ID", id);
		pc.put("CMD_MSG", msg);
		DBManager.getAccessExecuter().create(sql,pc);
		return id;
	}

	/**
	 * 读组态数据库反控结果(每秒一次)
	 * @param id
	 * @param time
	 * @return
	 */
	public static List<Row> readRcResult(String id,long time){
		List<Row> rows = null;
		String sql = "select cmd_result,cmd_response from RemoteControlT_Report where cmd_id = @CMD_ID" +
				" and cmd_result is not null";
		SQLParameterList pc = new SQLParameterList();
		pc.put("CMD_ID", id);

		long begintime = System.currentTimeMillis();
		long oldtime = begintime;
		while(true){
			long newtime = System.currentTimeMillis();
			if(newtime - oldtime >= 3000 ){
				rows = DBManager.getAccessExecuter().queryList(sql,pc);
				if(rows.size()>0){
					break;
				}
				oldtime = newtime;
			}
			if(newtime - begintime >= time){
				break;
			}
		}
		return rows;
	}



	/**
	 * 获取完整报文
	 * @param msg
	 * @return
	 */
	public static String getCompleteMsg(String msg){

		final int dataLengthFormat = 4;
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		StringBuilder strBuilder = new StringBuilder();

		strBuilder.append(msg);

		String crcStr = CRCUtil.calcCRC(strBuilder.toString());

		String dataLength = strBuilder.length() + "";
		while (dataLength.length() < dataLengthFormat) {
			dataLength = "0" + dataLength;
		}

		strBuilder.insert(0, "##" + dataLength);

		strBuilder.append(crcStr + "\r\n");
		return strBuilder.toString();
	}
}
